package com.example.app.api;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.app.common.Result;
import com.example.app.common.PageResult;
import com.example.application.RoleService;
import com.example.infra.po.RolePo;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/admin/roles")
@RequiredArgsConstructor
public class AdminRoleController {

    private final RoleService roleService;

    @GetMapping
    public Result<List<RolePo>> list(@RequestParam(value = "keyword", required = false) String keyword) {
        LambdaQueryWrapper<RolePo> qw = new LambdaQueryWrapper<>();
        if (keyword != null && !keyword.isEmpty()) {
            qw.like(RolePo::getRoleName, keyword);
        }
        return Result.success(roleService.list(qw));
    }

    @GetMapping("/page")
    public Result<PageResult<RolePo>> page(
            @RequestParam(value = "page", defaultValue = "1") Long pageNum,
            @RequestParam(value = "size", defaultValue = "10") Long pageSize,
            @RequestParam(value = "keyword", required = false) String keyword) {
        LambdaQueryWrapper<RolePo> qw = new LambdaQueryWrapper<>();
        if (keyword != null && !keyword.isEmpty()) {
            qw.like(RolePo::getRoleName, keyword);
        }
        Page<RolePo> page = new Page<>(pageNum, pageSize);
        roleService.page(page, qw);
        return Result.success(PageResult.of(page));
    }

    @PostMapping
    public Result<Boolean> create(@RequestBody RolePo role) {
        return Result.success(roleService.save(role));
    }

    @PutMapping("/{id}")
    public Result<Boolean> update(@PathVariable Integer id, @RequestBody RolePo role) {
        role.setId(id);
        return Result.success(roleService.updateById(role));
    }

    @DeleteMapping("/{id}")
    public Result<Boolean> remove(@PathVariable Integer id) {
        return Result.success(roleService.removeById(id));
    }
}


